package com.leonzx.base.controller.userpermission;

import com.jfinal.plugin.redis.Redis;
import com.leonzx.base.config.pager.Page;
import com.leonzx.base.config.pager.PageInfo;
import com.leonzx.base.controller.base.BaseController;
import com.leonzx.base.entity.system.User;
import com.leonzx.base.service.RedisService;
import com.leonzx.base.service.system.UserService;
import com.leonzx.base.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author:梁亮
 * @Description:
 * @Date: 2018/7/4 9:31
 */
@RestController
@RequestMapping("/ajax/userpermission/onlineuser")
public class AjaxOnlineUserController extends BaseController {

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserService userService;

    @RequestMapping("/list")
    public Map<String, Object> list(User user, @PageInfo(pageSize = Page.PAGE_SIZE, orderBy = "create_time", orderDiv = Page.Sort.DESC) Page<User> page) {
        Map<String, Object> result = getMap();
        try {
            List<String> usernames = redisService.getOnlineUsernames();
            List<User> users = userService.getUserByUsernames(usernames, user.getName(), user.getUsername());
            page.setResult(users);
            //循环list，处理数据
            for (User u : users) {
                String createTimeStr = redisService.getValue(RedisConstants.SHIRO_REDIS_USER_LOGIN_TIME + ":" + u.getUsername());
                String ip = redisService.getValue(RedisConstants.SHIRO_REDIS_USER_LOGIN_IP + ":" + u.getUsername());
                u.setCreateUserName(ip);
                u.setCreateTimeStr(createTimeStr);
            }
            result.put("count", page.getTotalCount());
            result.put("data", users);
            result.put("code", "0");
            result.put("msg", "加载完成");
        } catch (Exception e) {
            addFailMessage(result, "获取在线用户失败");
            logger.error("获取在线用户失败", e);
        }
        return result;
    }

    @RequestMapping("/outline")
    public Map<String, Object> outline(String username) {
        Map<String, Object> result = getMap();
        try {
            userService.outLine(username);
            addSuccessMessage(result, "下线成功");
        } catch (Exception e) {
            logger.error("下线失败", e);
            addFailMessage(result, "下线失败");
        }
        return result;
    }

}
